<?php
namespace api\models;
use common\helpers\Helper;
use common\models\LuckCard;

use Yii;
use yii\base\Model;
use wsl\ip2location\Ip2Location;


/**
 * 注册表单
 */
class LoginForm extends Model
{
    public $name;
    public $header;
    public $unionid;

    public function rules()
    {
        return [
            [['name', 'header','unionid'], 'required'],
            [['header'], 'string', 'max' => 200],
        ];
    }

    public function load($data, $formName = null){
        $rs = true;

        $fields = ['name','header','unionid'];
        foreach ($fields as $field){
            if(!isset($data[$field]) || empty($data[$field])){
                $rs = false;
                $this->addError($field,'不能为空');
                break;
            }else{
                $this->setAttributes([$field => $data[$field]]);
            }
        }

        return $rs;
    }

    public function login(){
        $user = User::getUserByUnionId($this->unionid);
        if(empty($user)){
            $user = $this->register();
        }else{
            //登录更新token
            $user->access_token = Yii::$app->security->generateRandomString();
            $user->token_expire = strtotime('+30 days');
            $user->save();
        }
        return $user;

    }

    private function register(){
        $user = new User();
        $user->name = $this->name;
        $user->header = $this->header;
        $user->unionid = $this->unionid;
        $user->access_token = Yii::$app->security->generateRandomString();
        $user->token_expire = strtotime('+30 days');
        $user->status = User::STATUS_ACTIVE;
        $user->award_num = 0;
        $user->bet_num = 0;
        $user->bet_win = 0;
        $inserted = $user->save();

        return $inserted ? $user : [];

    }

}
